package top.lishuoboy.shiro.realm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import top.lishuoboy.dependency.base.json.HuJsonUtil;
import top.lishuoboy.shiro.bean.User;

/**
 * 4.5 自定义Realm领域，将认证数据来源从配置文件shiro.ini改为从数据库获取
 *
 * @author lishuoboy
 * @date 2022/2/15 13:26
 */
@Slf4j
public class CustomizeRealm extends AuthorizingRealm {
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("== 授权 doGetAuthorizationInfo==================");
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("== 认证 doGetAuthenticationInfo==================");
        //在token中获取用户名
        String principal = (String) token.getPrincipal();
        Object credentials = token.getCredentials();
        log.debug("用户输入的用户名 principal=={}", principal);
        log.debug("用户输入的密码 credentials=={}", HuJsonUtil.toJsonStr(credentials));
        // 模拟 根据身份信息使用jdbc mybatis查询数据库中的 用户名、密码 等 用户信息
//        select * from user where name = 'principal'
        User user = new User().setName("zhangsan").setPwd("111111");

        if (user != null && user.getName().equals(principal)) {
            //参数1:返回数据库中正确的用户名   //参数2:返回数据库中正确密码  //参数3:提供当前realm的名字 this.getName();
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal, user.getPwd(), this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
